﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using IOP.SgrA;
using IOP.SgrA.SilkNet.Vulkan;
using System.Text.Json;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Drawing;
using Silk.NET.Vulkan;
using Microsoft.Extensions.Logging;

namespace VkSample71
{
    [ModulePriority(ModulePriority.RenderGroup)]
    public class PipelineModule : VulkanModule, IVulkanRenderWapperModule
    {
        public VulkanRenderWapper RenderWapper { get; set; }

        protected override async Task Load(VulkanGraphicsManager graphicsManager)
        {
            try
            {
                var lDevice = graphicsManager.VulkanDevice;
                var pipeCache = lDevice.PipelineCache;
                var disapatcher = RenderWapper.GetRenderDispatcher<VulkanSwapchainRenderDispatcher>();
                var pass = disapatcher.GetSwapchainRenderPass();
                var area = RenderWapper.RenderArea;
                var basePath = AppContext.BaseDirectory;
                var shaders = Path.Combine(basePath, "Assets", "Shaders");

                var command = lDevice.CreateCommandPool((device, option) =>
                {
                    option.Flags = CommandPoolCreateFlags.CommandPoolCreateResetCommandBufferBit;
                    option.QueueFamilyIndex = device.WorkQueues[0].FamilyIndex;
                }).CreatePrimaryCommandBuffer();
                var fence = lDevice.CreateFence();
                var mainGroup = graphicsManager.CreatePrimaryRenderGroup("MainRenderGroup", null)
                    .Binding(command, lDevice, pass, new Semaphore[] { disapatcher.ImageAvailableSemaphore, disapatcher.RenderFinishSemaphore }, new Fence[] { fence.RawHandle });
                mainGroup.CreateGroupRenderingAction((builder) => builder.UseMiddleware<MainGroupRenderingMiddleware>());

                VulkanShaderInfo[] infos = new VulkanSPVShaderInfo[]
                {
                new VulkanSPVShaderInfo(ShaderTypes.VertexShader, "commonVert", new FileInfo(Path.Combine(shaders,"vert.spv"))),
                new VulkanSPVShaderInfo(ShaderTypes.FragmentShader, "commonFrag", new FileInfo(Path.Combine(shaders, "frag.spv")))
                };
                await Task.WhenAll(infos[0].LoadShader(), infos[1].LoadShader());

                JsonDocument json = await JsonDocument.ParseAsync(File.OpenRead(Path.Combine(shaders, "pipeline.json")));
                var setLayoutJson = json.RootElement.GetProperty("DescriptorSetLayoutCreateOptions").ToString();
                var layoutJson = json.RootElement.GetProperty("PipelineLayoutCreateOption").ToString();
                var pipelineJson = json.RootElement.GetProperty("Pipeline").ToString();
                GraphicsPipelineCreateOption pipelineOption = JsonSerializer.Deserialize<GraphicsPipelineCreateOption>(pipelineJson);
                var pipeline = graphicsManager.CreateEmptyPipeline($"MainPipline")
                    .BuildPipelineLayoutFromJson(setLayoutJson, layoutJson)
                    .BuildUniformBuffer(0, 0, sizeof(float), SharingMode.Exclusive)
                    .BuildGraphicsPipeline(mainGroup.RenderPass, pipeCache, infos, pipelineOption);
                var sCommand = lDevice.CreateCommandPool((device, option) =>
                {
                    option.Flags = CommandPoolCreateFlags.CommandPoolCreateResetCommandBufferBit;
                    option.QueueFamilyIndex = device.WorkQueues[0].FamilyIndex;
                }).CreateSecondaryCommandBuffer();
                var aspect = (float)area.Width / area.Height;
                var secondary = graphicsManager.CreateSecondaryVulkanRenderGroup("FlatGroup", pipeline)
                    .Binding(mainGroup, sCommand, new VulkanSemaphore[0], new VulkanFence[0]);
                var camera = graphicsManager.CreateCamera("main", new Vector3(0, 0, 1.0f), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
                camera.SetProjectMatrix(-aspect, 1.0f, 1.5f, 1000);
                camera.SetViewport(0, 0, area.Width, area.Height, 0, 1);
                secondary.SetCamera(camera);
                secondary.CreateGroupRenderingAction((builder) => builder.UseMiddleware<SecondaryRenderingMiddleware>());
                secondary.CreateItemRenderingAction((builder) => builder.UseMiddleware<GroupItemMiddleware>());
                secondary.CreateInitializationAction((group) =>
                {
                    var uBuffer = group.Pipeline.GetPipelineTexture(0, 0);
                    float[] uData = new float[] { 0.9f };
                    var bData = MemoryMarshal.AsBytes<float>(uData);
                    uBuffer.UpdateTextureMemoryData(bData);
                });

                RenderWapper.CreateAndCutScene<Scene>("main", mainGroup, typeof(TransformSystem));
            }
            catch (Exception e)
            {
                graphicsManager.Logger.LogError(e.Message);
            }
        }

        protected override Task Unload(VulkanGraphicsManager manager)
        {
            return Task.CompletedTask;
        }
    }
}
